package com.cloud.bc.service.impl;

import com.cloud.bc.model.entity.BcFriends;
import com.cloud.bc.model.entity.BcMomen;
import com.cloud.bc.mapper.BcMomenMapper;
import com.cloud.bc.model.entity.BcMomenComments;
import com.cloud.bc.model.entity.BcMomenPraises;
import com.cloud.bc.model.request.MomenRequest;
import com.cloud.bc.model.response.MomenSingleResponse;
import com.cloud.bc.service.*;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 动态
 *
 * @author douhaichao code generator
 * @date 2021-01-15 14:42:48
 */
@Service
@AllArgsConstructor
public class BcMomenServiceImpl extends ServiceImpl<BcMomenMapper, BcMomen> implements BcMomenService {
    private final BcFriendsService bcFriendsService;
    private final BcSinglesService bcSinglesService;
    private final BcMomenCommentsService bcMomenCommentsService;
    private final BcMomenPraisesService bcMomenPraisesService;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcMomen selectOne(BcMomen req) {
        QueryWrapper queryWrapper = new QueryWrapper<BcMomen>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcMomen> selectAll(BcMomen req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcMomen> selectPage(Page page, BcMomen req) {
        IPage<BcMomen> list = baseMapper.selectPage(
                page,
                new QueryWrapper<BcMomen>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<BcMomen> selectPageByLike(Page page, BcMomen req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getId()) {
            queryWrapper.eq("id", req.getId());
        }

        if (null != req.getUserId()) {
            queryWrapper.eq("user_id", req.getUserId());
        }

        if (null != req.getType()) {
            queryWrapper.eq("type", req.getType());
        }

        if (!StrUtil.isEmpty(req.getContent())) {
            queryWrapper.like("content", req.getContent());
        }

        if (!StrUtil.isEmpty(req.getMedia())) {
            queryWrapper.like("media", req.getMedia());
        }

        if (!StrUtil.isEmpty(req.getMediaType())) {
            queryWrapper.like("media_type", req.getMediaType());
        }

        if (!StrUtil.isEmpty(req.getLatitude())) {
            queryWrapper.like("latitude", req.getLatitude());
        }

        if (!StrUtil.isEmpty(req.getLongitude())) {
            queryWrapper.like("longitude", req.getLongitude());
        }

        if (!StrUtil.isEmpty(req.getLocation())) {
            queryWrapper.like("location", req.getLocation());
        }

        if (null != req.getPraise()) {
            queryWrapper.eq("praise", req.getPraise());
        }

        if (null != req.getComments()) {
            queryWrapper.eq("comments", req.getComments());
        }

        if (null != req.getIsCheck()) {
            queryWrapper.eq("is_check", req.getIsCheck());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }

        if (null != req.getIsDel()) {
            queryWrapper.eq("is_del", req.getIsDel());
        }
        IPage<BcMomen> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcMomen req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public IPage<BcMomen> getMomenSearchList(Page page, MomenRequest req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (req.getOrderBy().equals("friend")) {
            //好友
            List<BcFriends> listFriends = bcFriendsService.selectFriendIds(req.getUserId());
            Set<Integer> userIds = new HashSet<>();
            if (null != listFriends && listFriends.size() > 0) {
                Set<Integer> userId = listFriends.stream().
                        filter(t -> !t.getUserId().equals(req.getUserId())).
                        map(t -> t.getUserId()).collect(Collectors.toSet());
                Set<Integer> targetId = listFriends.stream().
                        filter(t -> !t.getTargetId().equals(req.getUserId())).
                        map(t -> t.getTargetId()).collect(Collectors.toSet());
                userIds.addAll(userId);
                userIds.addAll(targetId);
            }
            if (null != userIds && userIds.size() > 0) {
                queryWrapper.in("user_id", userIds);
            }
        } else if (req.getOrderBy().equals("me")) {
            //我自己
            queryWrapper.eq("user_id", req.getUserId());
        }
        queryWrapper.orderByDesc("id");
        IPage iPage = baseMapper.selectPage(page, queryWrapper);
        List<BcMomen> records = iPage.getRecords();
        if (null == records || records.size() <= 0) {
            return null;
        }
        Set<Integer> userIds = records.stream().map(t -> t.getUserId()).collect(Collectors.toSet());
        List<MomenSingleResponse> listSinlge = bcSinglesService.selectMomenSingle(userIds);
        if (null != listSinlge || listSinlge.size() > 0) {
            records.forEach(item -> {
                MomenSingleResponse momenSingleResponse = listSinlge.stream().
                        filter(t -> t.getUserId().equals(item.getUserId())).
                        findFirst().orElse(new MomenSingleResponse());
                momenSingleResponse.setAge(bcSinglesService.ageConvert(momenSingleResponse.getBirthday()));
                item.setSingle(momenSingleResponse);
                if (item.getUserId().equals(req.getUserId())) {
                    //是自己
                    item.setIssuer(true);
                }
            });
        }

        //查询出单身圈ID
        Set<Integer> momenIds = records.stream().map(t -> t.getId()).collect(Collectors.toSet());
        //查询所有点赞
        QueryWrapper queryWrapperMomenPraises = new QueryWrapper();
        queryWrapperMomenPraises.in("moment_id", momenIds);
        List<BcMomenPraises> listMomenPraises = bcMomenPraisesService.list(queryWrapperMomenPraises);
        //查询所有评论
        List<BcMomenComments> listComments = bcMomenCommentsService.list(queryWrapperMomenPraises);
        records.forEach(item -> {
            //点赞列表
            List<BcMomenPraises> listPraises = listMomenPraises.stream().filter(t -> t.getMomentId().equals(item.getId())).collect(Collectors.toList());
            item.setPraises(listPraises);
            //是否有过点赞
            long isPraise = listPraises.stream().filter(t -> t.getUserId().equals(req.getUserId())).count();
            item.setExistsPraise(isPraise > 0 ? true : false);
            //是否有过点赞
            //评论
            List<BcMomenComments> listComment = listComments.stream().filter(t -> t.getMomentId().equals(item.getId())).collect(Collectors.toList());
            item.setCommentList(listComment);
        });
        return iPage;
    }

    @Override
    public void commentCount(Integer momentId) {
        baseMapper.commentCount(momentId);
    }

    @Override
    public void commentUnCount(Integer momentId) {
        baseMapper.commentUnCount(momentId);
    }
}
